package com.example.robertluozizhao.java.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 注意
 * 1.实现Callable 复写call方法
 * 2.FutureTask 为载体 可通过它 get获取线程返回结果
 * 3.get方法线程未执行完 会阻塞
 *
 * Created by Lzz on 7/18/2019.
 */

public class CallThreadDemo implements Callable<Integer>{


    public static void main(String args[]){

        CallThreadDemo callThreadDemo = new CallThreadDemo();
        FutureTask futureTask = new FutureTask(callThreadDemo);
        new Thread(futureTask).start();
        System.out.println("执行了  new Thread(futureTask).start()");

        CallThreadTest callThreadTest = new CallThreadTest();
        FutureTask<String> stringFutureTask = new FutureTask<>(callThreadTest);
        new Thread(stringFutureTask).start();
        System.out.println("执行了  new Thread(stringFutureTask).start()");

        try {
            int result = (int) futureTask.get();
            String result1 =  stringFutureTask.get();
            System.out.println("callThreadDemo result："+result);
            System.out.println("callThreadTest result1："+result1);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("************结果输出完毕************");

    }


    @Override
    public Integer call() throws Exception {
        Thread.sleep(10000);
        return 2;
    }

    public static class CallThreadTest implements Callable<String>{
        @Override
        public String call() throws Exception {
            Thread.sleep(5000);
            return "CallThreadTest";
        }
    }


}
